package com.moyun.modelclass.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.activity.AddressListActivity;
import com.moyun.modelclass.activity.ArticleHistoryActivity;
import com.moyun.modelclass.activity.ChatDetailActivity;
import com.moyun.modelclass.activity.CreatorCenterActivity;
import com.moyun.modelclass.activity.FansAndFollowsActivity;
import com.moyun.modelclass.activity.InvitationCodeActivity;
import com.moyun.modelclass.activity.LoginVerificationCodeActivity;
import com.moyun.modelclass.activity.MyArticleActivity;
import com.moyun.modelclass.activity.MyCollectActivity;
import com.moyun.modelclass.activity.MyModelActivity;
import com.moyun.modelclass.activity.MyOrderActivity;
import com.moyun.modelclass.activity.PersonalInformationActivity;
import com.moyun.modelclass.activity.VipActivity;
import com.moyun.modelclass.activity.WebRichActivity;
import com.moyun.modelclass.adapter.MineMoreAdapter;
import com.moyun.modelclass.base.BaseFragment;
import com.moyun.modelclass.event.LoginStateEvent;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.FundInfoApi;
import com.moyun.modelclass.http.api.MemberInfoApi;
import com.moyun.modelclass.http.api.UserCenterPageApi;
import com.moyun.modelclass.http.api.UserInfoApi;
import com.moyun.modelclass.http.bean.LoginInfoResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;

/**
 * 作者：Meteor
 * 日期：2022/1/19 23:25
 * tip：我的
 */
public class MainMineFragment extends BaseFragment implements MineMoreAdapter.OnItemSelectedChangedListener {
    private ImageView ivMineBackgroundImage;
    private ImageView mainMineHeadPortrait;
    private ImageView mainMineWechatTip;
    private TextView mainMineName;
    private ImageView mainMineGender;
    private ImageView mainMineVipStatus;
    private TextView mainMineLoginTip;
    private TextView mainMineBalance;
    private ImageView mainMineNext;
    private TextView tvMainMineTitle;
    private LinearLayout llMainMineFans;
    private TextView tvMainMineFans;
    private LinearLayout llMainMineFollow;
    private TextView tvMainMineFollow;
    private LinearLayout llMainMineArticle;
    private TextView tvMainMineArticle;
    private TextView mainMineOrderHyzx;
    private TextView mainMineCzzzx;
    private TextView mainMineYqm;
    private TextView mainMineWddd;
    private TextView mainMineOrderWdmx;
    private TextView mainMineWdwz;
    private TextView mainMineWdsc;
    private TextView mainMineLljl;
    private RelativeLayout mainMineShdz;
    private RelativeLayout mainMineGfkf;
    private TextView tvMainMineGfkf;
    private RelativeLayout mainMineBzzx;
    private RelativeLayout mainMineGywm;
    private RecyclerView recyclerMainMineMore;

    private DecimalFormat df = new DecimalFormat("￥##0.00");
    private UserCenterPageApi.CustomerServiceConfigBean customerServiceConfig = null;
    private MineMoreAdapter mineMoreAdapter = new MineMoreAdapter();


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main_mine;
    }

    @Override
    protected void assignViews(View view) {
        ivMineBackgroundImage = (ImageView) view.findViewById(R.id.iv_mine_background_image);
        mainMineHeadPortrait = (ImageView) view.findViewById(R.id.main_mine_head_portrait);
        mainMineWechatTip = (ImageView) view.findViewById(R.id.main_mine_wechat_tip);
        mainMineName = (TextView) view.findViewById(R.id.main_mine_name);
        mainMineGender = (ImageView) view.findViewById(R.id.main_mine_gender);
        mainMineVipStatus = (ImageView) view.findViewById(R.id.main_mine_vip_status);
        mainMineLoginTip = (TextView) view.findViewById(R.id.main_mine_login_tip);
        mainMineBalance = (TextView) view.findViewById(R.id.main_mine_balance);
        mainMineNext = (ImageView) view.findViewById(R.id.main_mine_next);
        tvMainMineTitle = (TextView) view.findViewById(R.id.tv_main_mine_title);
        llMainMineFans = (LinearLayout) view.findViewById(R.id.ll_main_mine_fans);
        tvMainMineFans = (TextView) view.findViewById(R.id.tv_main_mine_fans);
        llMainMineFollow = (LinearLayout) view.findViewById(R.id.ll_main_mine_follow);
        tvMainMineFollow = (TextView) view.findViewById(R.id.tv_main_mine_follow);
        llMainMineArticle = (LinearLayout) view.findViewById(R.id.ll_main_mine_article);
        tvMainMineArticle = (TextView) view.findViewById(R.id.tv_main_mine_article);
        mainMineOrderHyzx = (TextView) view.findViewById(R.id.main_mine_order_hyzx);
        mainMineCzzzx = (TextView) view.findViewById(R.id.main_mine_czzzx);
        mainMineYqm = (TextView) view.findViewById(R.id.main_mine_yqm);
        mainMineWddd = (TextView) view.findViewById(R.id.main_mine_wddd);
        mainMineOrderWdmx = (TextView) view.findViewById(R.id.main_mine_order_wdmx);
        mainMineWdwz = (TextView) view.findViewById(R.id.main_mine_wdwz);
        mainMineWdsc = (TextView) view.findViewById(R.id.main_mine_wdsc);
        mainMineLljl = (TextView) view.findViewById(R.id.main_mine_lljl);
        mainMineShdz = (RelativeLayout) view.findViewById(R.id.main_mine_shdz);
        mainMineGfkf = (RelativeLayout) view.findViewById(R.id.main_mine_gfkf);
        tvMainMineGfkf = (TextView) view.findViewById(R.id.tv_main_mine_gfkf);
        mainMineBzzx = (RelativeLayout) view.findViewById(R.id.main_mine_bzzx);
        mainMineGywm = (RelativeLayout) view.findViewById(R.id.main_mine_gywm);
        recyclerMainMineMore = (RecyclerView) view.findViewById(R.id.recycler_main_mine_more);

//        StatusBarUtil.setPaddingSmart(requireActivity(), llMainMineTop);

        recyclerMainMineMore.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerMainMineMore.addItemDecoration(new DividerItemDecoration(mContext, Color.parseColor("#EEEFEF"), 1, SizeUtils.dp2px(15), SizeUtils.dp2px(15), false));
        mineMoreAdapter.setOnItemSelectedChangedListener(this);
        recyclerMainMineMore.setAdapter(mineMoreAdapter);
    }

    @Override
    protected void registerListeners() {
        //头像
        ClickUtils.applySingleDebouncing(mainMineHeadPortrait, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    PersonalInformationActivity.start(mContext);
                } else {
                    LoginVerificationCodeActivity.start(mContext);
                }
            }
        });

        //个人信息编辑
        ClickUtils.applySingleDebouncing(mainMineNext, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    PersonalInformationActivity.start(mContext);
                } else {
                    LoginVerificationCodeActivity.start(mContext);
                }
            }
        });

        //关注
        ClickUtils.applySingleDebouncing(llMainMineFollow, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    FansAndFollowsActivity.start(requireActivity(), 0);
                } else {
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //粉丝
        ClickUtils.applySingleDebouncing(llMainMineFans, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    FansAndFollowsActivity.start(requireActivity(), 1);
                } else {
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //文章
        ClickUtils.applySingleDebouncing(llMainMineArticle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    MyArticleActivity.start(requireActivity());
                } else {
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //会员中心
        ClickUtils.applySingleDebouncing(mainMineOrderHyzx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    VipActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //创作者中心
        ClickUtils.applySingleDebouncing(mainMineCzzzx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    CreatorCenterActivity.start(requireActivity(), CommonConfiguration.getUseId(kv));
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //邀请码
        ClickUtils.applySingleDebouncing(mainMineYqm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    InvitationCodeActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //我的订单
        ClickUtils.applySingleDebouncing(mainMineWddd, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    MyOrderActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //我的模型
        ClickUtils.applySingleDebouncing(mainMineOrderWdmx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    MyModelActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //我的文章
        ClickUtils.applySingleDebouncing(mainMineWdwz, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    MyArticleActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //我的收藏
        ClickUtils.applySingleDebouncing(mainMineWdsc, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    MyCollectActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //浏览记录
        ClickUtils.applySingleDebouncing(mainMineLljl, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    ArticleHistoryActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //收货地址
        ClickUtils.applySingleDebouncing(mainMineShdz, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    AddressListActivity.start(requireActivity());
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        //官方客服
        ClickUtils.applySingleDebouncing(mainMineGfkf, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (customerServiceConfig != null) {
                    if (CommonConfiguration.isLogin(kv)) {
                        ChatDetailActivity.start(requireActivity(), customerServiceConfig.getUserId(), customerServiceConfig.getPhone());
                    }else {
//                        ToastUtils.showShort(getString(R.string.http_token_error));
                        LoginVerificationCodeActivity.start(requireActivity());
                    }
                }
            }
        });

        //帮助中心
        ClickUtils.applySingleDebouncing(mainMineBzzx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebRichActivity.start(mActivity, "HelpCenter");
            }
        });

        //关于我们
        ClickUtils.applySingleDebouncing(mainMineGywm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebRichActivity.start(mActivity, "AboutUs");
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        Log.e("MainMineFragment", "doAction");
    }

    @Override
    public void onStart() {
        super.onStart();
        initUserInfo();
        ConfigUserCenterPage();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initUserInfo();
        }
    }

    private void initUserInfo() {
        String userId = CommonConfiguration.getUseId(kv);
        if (userId == null || userId.isEmpty()) {
            setLoginState(null);
            return;
        }
        initMemberInfo();
        initUserInfoApi();
    }

    //获取用户信息
    private void initUserInfoApi() {
        EasyHttp.post(requireActivity())
                .api(new UserInfoApi().setUserId(CommonConfiguration.getUseId(kv)))
                .request(new HttpCallback<HttpData<LoginInfoResponse>>(this) {
                    @Override
                    public void onSucceed(HttpData<LoginInfoResponse> result) {
                        setLoginState(result.getData());
                    }
                });
    }

    //获取用户会员信息
    @SuppressLint("SetTextI18n")
    private void initMemberInfo() {
        EasyHttp.post(this)
                .api(new MemberInfoApi())
                .request(new HttpCallback<HttpData<MemberInfoApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<MemberInfoApi.Bean> result) {
                        if (result.getData() != null) {
                            if (result.getData().getLevel() == 1) {
                                mainMineVipStatus.setVisibility(View.GONE);
                            } else {
                                mainMineVipStatus.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void setLoginState(LoginInfoResponse response) {
        Glide.with(requireActivity())
                .asBitmap()
                .load(response == null ? R.drawable.icon_head_portrait : CommonConfiguration.splitResUrl(3, response.getAvatar()))
                .placeholder(R.drawable.icon_head_portrait)
                .error(R.drawable.icon_head_portrait)
                .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                .into(new BitmapImageViewTarget(mainMineHeadPortrait) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        mainMineHeadPortrait.setImageBitmap(ImageUtils.toRound(resource));
                    }
                });

        if (response == null) {
            mainMineWechatTip.setVisibility(View.GONE);
            mainMineName.setVisibility(View.GONE);
            mainMineGender.setVisibility(View.GONE);
            mainMineLoginTip.setVisibility(View.VISIBLE);
            mainMineNext.setVisibility(View.GONE);
            tvMainMineTitle.setVisibility(View.GONE);
            mainMineBalance.setVisibility(View.GONE);
            mainMineVipStatus.setVisibility(View.GONE);
            tvMainMineFans.setText("0");
            tvMainMineFollow.setText("0");
            tvMainMineArticle.setText("0");
        } else {
            EventBus.getDefault().post(new LoginStateEvent(1));
            Glide.with(requireActivity())
                    .asBitmap()
                    .load(CommonConfiguration.splitResUrl(6, response.getBackgroundImage()))
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(new BitmapImageViewTarget(ivMineBackgroundImage) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            super.setResource(resource);
                            ivMineBackgroundImage.setImageBitmap(resource);
                        }
                    });
            mainMineName.setText(response.getNickName());
            Glide.with(requireActivity())
                    .load(response.getGender() == 1 ? R.drawable.icon_man : R.drawable.icon_woman)
                    .centerInside()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(mainMineGender);
            tvMainMineTitle.setText(response.getDesc());

            mainMineBalance.setVisibility(View.VISIBLE);
            mainMineBalance.setText("余额：" + df.format(response.getBalance() * 0.01));

            tvMainMineFans.setText(String.valueOf(response.getFansCount()));
            tvMainMineFollow.setText(String.valueOf(response.getFollowerCount()));
            tvMainMineArticle.setText(String.valueOf(response.getArticleCount()));

            mainMineWechatTip.setVisibility(response.isHasBindWechat() ? View.VISIBLE : View.GONE);
            mainMineName.setVisibility(View.VISIBLE);
            mainMineGender.setVisibility(View.VISIBLE);
            mainMineLoginTip.setVisibility(View.GONE);
            mainMineNext.setVisibility(View.VISIBLE);
            tvMainMineTitle.setVisibility(View.VISIBLE);
        }
    }

    private void ConfigUserCenterPage() {
        EasyHttp.post(this)
                .api(new UserCenterPageApi())
                .request(new HttpCallback<HttpData<UserCenterPageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UserCenterPageApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            tvMainMineGfkf.setText(result.getData().getCustomerServiceConfig().getDesc());
                            customerServiceConfig = result.getData().getCustomerServiceConfig();
                            mineMoreAdapter.setList(result.getData().getMenuItemConfigList());
                        }
                    }
                });
    }

    @Override
    public void onItemSelected(String url) {
        CommonConfiguration.skipNewPage(requireActivity(), url);
    }
}
